import axios from 'axios'
import { Message, Loading } from 'element-ui'
import { getToken, setToken, removeToken } from './auth'
import { emptyStrToNull } from "@/utils";
const auth = 'token';
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 5000000
})
let loading        //定义loading变量

function tokenInvalidation (msg) {
  removeToken();
  Message({
    message: msg,
    type: 'warning',
    showClose: true,
    onClose: () => {
      // const hash = window.location.search.slice(1);
      // window.location.href = window.location.origin + '/login#' + hash;
    }
  })
}


function startLoading () {    //使用Element loading-start 方法
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(255,255,255,0)'
  })
}
function endLoading () {    //使用Element loading-close 方法
  loading.close()
}
//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
service.interceptors.request.use(
  config => {
    if (config.url != "/login") {
      config.headers[auth] = `${getToken()}`
      config.headers['Content-Type'] = `application/json`
      config.headers['post']['Content-Type'] = 'application/json'
      config.headers['put']['Content-Type'] = 'application/json'
    }
    if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
      showFullScreenLoading()
    }
    //判断数据类型FormData类型不转
    if (!(config.data instanceof FormData)) {
      config.data = emptyStrToNull(JSON.parse(JSON.stringify(Object.assign({}, config.data))));//空串转null 上传时
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  // response =>  response.data,
  response => {
    tryHideFullScreenLoading()
    if (response.status !== 200) {
      Message({ message: response.statusText, type: 'error', duration: 3 * 1000 })
      return Promise.reject(response.statusText)
    }
    if (response.status === 200 && !response.data.success && response.data.toLocaleString() !== "[object Blob]") {
      Message({ message: response.data.message, type: 'error', duration: 3 * 1000 })
      return Promise.reject(response.data.message)
    }
    return response.data
  },
  error => {
    tryHideFullScreenLoading()
    if (error.response && error.response.status) {
      switch (error.response.status) {
        case 500:
          if (error.response.data.code === '000') {
            //token失效
            tokenInvalidation(error.response.data.message);
          }
          break;
        default:
          Message({
            message: error,
            type: 'error',
            duration: 5 * 1000
          })
          break;
      }
    } else {
      Message({ message: error, type: 'error', duration: 3 * 1000 })
    }
    //后期异常会直接跳转登录
    // console.log('error', error.response)
    // console.log('err' + error+",msg:" + JSON.stringify(error.response.data));

    // const hash = window.location.search.slice(1)
    // window.location.href = window.location.origin + '/login#' + hash
    return Promise.reject(error)
  }
)

export default service
